package com.ll.blog.controller;

import com.ll.blog.Exception.BlogException;
import com.ll.blog.common.ApiResponse;
import com.ll.blog.contant.Constant;
import com.ll.blog.contant.ExceptionEnum;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;


@RestController
@RequestMapping("upload")
public class UploadController {
    /**
     * 文件上传接口
     */
    @PostMapping("/")
    public ApiResponse upload(@RequestParam("file") MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String suffixname = null;
        if (filename != null) {
            suffixname = filename.substring(filename.lastIndexOf("."));
        }
        String newFilename = UUID.randomUUID() + suffixname;
        File dir = new File(Constant.FILE_UPLOAD_DIR);
        File destfile = new File(Constant.FILE_UPLOAD_DIR + newFilename);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                throw new RuntimeException();
            }
        }
        file.transferTo(destfile);
        HashMap<String, Object> map = new HashMap<>();
        map.put("img",Constant.FILE_UPLOAD_ID+"/images/"+newFilename);
        return ApiResponse.success(map);
    }
}
